package cn.samler.diandi.api.handler;

import cn.samler.diandi.api.model.io.Response;
import cn.samler.diandi.api.utils.ResponseBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;

@ControllerAdvice
@Slf4j
public class RequestExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Response handler(Exception e) {
//        e.printStackTrace();

        if (e instanceof MethodArgumentNotValidException) {
            ArrayList<String> msgList = new ArrayList<>();
            for (ObjectError err : ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors()) {
                msgList.add(err.getDefaultMessage());
            }

            return new ResponseBuilder().failure().msg("请求发生错误").data(msgList).build();
        }

        return new ResponseBuilder().failure().msg(e.getMessage()).build();
    }

}
